package com.hdu.h_health.internet;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.widget.ImageView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.hdu.h_health.R;

/**
 * 使用Volley网络通信库来实现新闻列表项图片和轮播图片加载
 * Created by 612 on 2015/10/24.
 */
public class ImageLoadUsingVolley {

    private LruCache<String, Bitmap> lruCache;//创建缓存对象

    public ImageLoadUsingVolley() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();//获取应用的可用缓存
        int cacheSize = maxMemory / 4;//设置图片的缓存大小
        lruCache = new LruCache<>(cacheSize);
    }

    /**
     * 从网络加载图片并设置给ImageView
     *
     * @param imageView 传入的ImageView对象
     * @param url 传入的网络图片地址
     */
    public void ImageLoad(Context context, ImageView imageView, String url) {
        //创建请求的队列
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String url) {
                return lruCache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                lruCache.put(url, bitmap);
            }
        });
        ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(imageView,
                R.drawable.loading, R.drawable.loading);
        imageLoader.get(url, imageListener, 400, 400);
    }
}
